/*
 * ZigZag Conversion
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
 */
package com.xinpan.exercise;

public class ZigZagConversion {
    public String convert(String s, int nRows) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(nRows == 1)
            return s;
    
        boolean down = true;
        String str = "";
        int gap = 2 * nRows - 2;
        for(int i = 0; i < s.length(); i += gap)
            str += s.charAt(i);
            
        for(int i = 1; i < nRows-1; i++)
        {
            down = true;
            for(int j = i; j < s.length();)
            {
                str += s.charAt(j);
                if(down)
                    j += (nRows-i-1)*2;
                else
                    j += i*2;
                down = !down;
            }
        }
        
        for(int i = nRows-1; i < s.length(); i += gap)
            str += s.charAt(i);
        
        return str;
    }
}
